package cly.thirdpartyconsumer.client;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import com.guigu.ssyx.common.result.Result;
import java.util.List;

@Component
public class UpstreamDataClient {
    private final WebClient webClient;

    public UpstreamDataClient() {
        this.webClient = WebClient.builder()
                .baseUrl("http://localhost:8097/api/data/sync-data")
                .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(10 * 1024 * 1024))
                .build();
    }

    /**
     * 获取指定类型的数据（如 users, orders, products, logistics）
     */
    public <T> List<T> fetchData(String type, Class<T> clazz) {
        try {
            String token = "your-access-token"; // 上游提供的 token

            Result<List<T>> response = webClient
                    .get()
                    .uri("/{type}", type)
                    .retrieve()
                    .bodyToMono(new ParameterizedTypeReference<Result<List<T>>>() {})
                    .block();

            if (response != null && response.getCode() == 200) {
                System.out.println("获取数据成功: " + response.getData());
                return response.getData();
            } else {
                throw new RuntimeException("上游接口调用失败: " + response.getMessage());
            }
        } catch (Exception e) {
            throw new RuntimeException("调用上游接口异常: " + e.getMessage(), e);
        }
    }
}
